// src/composables/dialog/useDialog.ts
import { h, type ComponentPublicInstance } from "vue";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import { ElLoading, ElMessageBox } from "element-plus";
import { message } from "@/utils/message";

type DialogComponentInstance =
  | (ComponentPublicInstance & {
      submitForm?: () => Promise<boolean>;
    })
  | null;

type DialogHook = (
  done: () => void,
  componentRef?: DialogComponentInstance
) => void | boolean | Promise<boolean | void>;

interface DialogOptions {
  title?: string;
  id?: string | number;
  width?: string;
  props?: Record<string, any>;
  onConfirm?: DialogHook;
  onCancel?: DialogHook;
  showCancelConfirm?: boolean;
  cancelConfirmText?: string;
  fullscreen?: boolean;
  draggable?: boolean;
  closeOnClickModal?: boolean;
  loadingText?: string;
  closeOnPressEscape?: boolean;
  showClose?: boolean;
}

const runHook = async (
  hook: DialogHook | undefined,
  done: () => void,
  componentRef: DialogComponentInstance,
  actionLabel: string
) => {
  if (!hook) {
    return { shouldContinue: true, alreadyClosed: false };
  }

  let alreadyClosed = false;

  const doneWrapper = () => {
    alreadyClosed = true;
    done();
  };

  try {
    const result = await hook(doneWrapper, componentRef);

    if (alreadyClosed) {
      return { shouldContinue: false, alreadyClosed: true };
    }

    if (typeof result === "boolean") {
      return { shouldContinue: result, alreadyClosed: false };
    }

    return { shouldContinue: true, alreadyClosed: false };
  } catch (error: any) {
    console.error(`执行${actionLabel}回调时出错:`, error);
    message(`${actionLabel}失败: ${error?.message || "未知错误"}`, {
      type: "error"
    });
    return { shouldContinue: false, alreadyClosed: false };
  }
};

const shouldCancelDialog = async (
  showConfirm: boolean,
  confirmText: string
) => {
  if (!showConfirm) {
    return true;
  }

  try {
    await ElMessageBox.confirm(confirmText, "提示", {
      type: "warning",
      confirmButtonText: "继续关闭",
      cancelButtonText: "留在此页"
    });
    return true;
  } catch (error) {
    return false;
  }
};

export function useDialog() {
  // 通用打开对话框方法
  const openDialog = async (component: any, options: DialogOptions = {}) => {
    const {
      title = "对话框",
      id = "",
      width = "60%",
      props = {},
      onConfirm,
      onCancel,
      showCancelConfirm = false,
      cancelConfirmText = "确认要关闭当前对话框吗？",
      fullscreen = deviceDetection(),
      draggable = true,
      closeOnClickModal = false,
      loadingText = "加载中...",
      closeOnPressEscape = true,
      showClose = true
    } = options;

    let componentRef: DialogComponentInstance = null;

    const loadingInstance = ElLoading.service({
      text: loadingText,
      background: "rgba(0, 0, 0, 0.7)"
    });

    try {
      const module = await Promise.resolve(
        typeof component === "function" ? component() : component
      );
      const resolvedComponent = module?.default || module;

      const resolvedProps = { ...props };
      if (id !== undefined && id !== null && resolvedProps.id === undefined) {
        resolvedProps.id = id;
      }

      addDialog({
        title,
        props: resolvedProps,
        width,
        draggable,
        fullscreen,
        fullscreenIcon: true,
        closeOnClickModal,
        closeOnPressEscape,
        showClose,
        contentRenderer: () =>
          h(resolvedComponent, {
            ...resolvedProps,
            ref: (ref: DialogComponentInstance) => {
              componentRef = ref;
            }
          }),
        beforeSure: async done => {
          const closeDialog = () => {
            (done as () => void)();
          };

          const { shouldContinue, alreadyClosed } = await runHook(
            onConfirm,
            closeDialog,
            componentRef,
            "提交"
          );

          if (alreadyClosed || shouldContinue === false) {
            return;
          }

          if (componentRef?.submitForm) {
            try {
              const success = await componentRef.submitForm();
              if (success) {
                closeDialog();
              }
            } catch (error: any) {
              console.error("提交表单时出错:", error);
              message(`提交失败: ${error?.message || "未知错误"}`, {
                type: "error"
              });
            }
          } else {
            closeDialog();
          }
        },
        beforeCancel: async done => {
          const closeDialog = () => {
            (done as () => void)();
          };

          const allowClose = await shouldCancelDialog(
            showCancelConfirm,
            cancelConfirmText
          );
          if (!allowClose) {
            return;
          }

          const { shouldContinue, alreadyClosed } = await runHook(
            onCancel,
            closeDialog,
            componentRef,
            "取消"
          );

          if (alreadyClosed) {
            return;
          }

          if (shouldContinue) {
            closeDialog();
          }
        }
      });
    } catch (error: any) {
      console.error("加载组件失败:", error);
      message(`加载组件失败: ${error?.message || "未知错误"}`, {
        type: "error"
      });
    } finally {
      loadingInstance.close();
    }
  };

  return {
    openDialog
  };
}
